package com.qdaily.ui.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.updateapp.ApkDownloadService;
import com.qdaily.supportlibrary.util.ImageUtil;
import com.qdaily.supportlibrary.util.NetUtil;
import com.qdaily.supportlibrary.util.QDJsonUtil;
import com.qdaily.ui.MainActivity;
import com.qdaily.ui.PhotoChoose.CropOption;
import com.qdaily.ui.PhotoChoose.PhotoReadyHandler;
import com.qdaily.ui.PhotoChoose.SelectPhotoManager;
import com.qdaily.ui.QDBaseFragment;
import com.qdaily.ui.R;
import com.qdaily.ui.data.Constants;
import com.qdaily.ui.data.UserInformation;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.entity.BaseEntity;
import com.qdaily.ui.net.entity.UserCenterEntity;
import com.qdaily.ui.ui.NextstepActivity;
import com.qdaily.ui.ui.views.TitleBar;
import com.qdaily.ui.util.BusProvider;
import com.squareup.otto.Subscribe;

import java.io.File;
import java.util.HashMap;

/**
 * 个人中心，就第三方这破逼玩意儿就应该干了它。现在是没时间暂用。FUCK
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/13/15
 * Time: 23:04
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class PersonalCenterFragment extends QDBaseFragment implements View.OnClickListener, PlatformActionListener {
    private ImageView imageViewPersonalCenterPhoto;
    private android.widget.TextView textViewPersonalCenterNickName;
    private android.widget.TextView textViewPersonalCenterDes;
    private android.widget.TextView textViewPersonalCenterEmail;
    private android.widget.TextView textViewPersonalCenterBindSina;
    private android.widget.TextView textViewPersonalCenterBindQQ;
    private android.widget.TextView textViewPersonalCenterBindWX;
    private android.widget.TextView textViewPersonalCenterLogout;
    private android.widget.ImageView imageViewPersonalCenterSinaSwitch;
    private android.widget.ImageView imageViewPersonalCenterQQSwitch;
    private android.widget.ImageView imageViewPersonalCenterWXSwitch;
    private ImageView imageViewPersonalCenterSinaLogo;
    private ImageView imageViewPersonalCenterQQLogo;
    private ImageView imageViewPersonalCenterWxLogo;
    private TitleBar personal_center_title;

    //third party
    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR = 2;

    //图片选择完的结果集。
    private File imageFile;

    private android.widget.LinearLayout linearLayoutPersonalCenterAvatar;
    private android.widget.LinearLayout linearLayoutPersonalCenterNickName;
    private android.widget.LinearLayout linearLayoutPersonalCenterDes;
    private android.widget.LinearLayout linearLayoutPersonalCenterEmail;
    private android.widget.LinearLayout linearLayoutPersonalCenterChangePwd;

    private MainActivity mContext;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_personal_center;
    }

    @Override
    protected void setupViews(View view) {
        this.personal_center_title = (TitleBar) view.findViewById(R.id.personal_center_title);
        personal_center_title.setTitle(R.string.i_center);
        personal_center_title.getImageViewTitleBarLeft().setVisibility(View.INVISIBLE);

        this.linearLayoutPersonalCenterChangePwd = (LinearLayout) view.findViewById(R.id.linearLayoutPersonalCenterChangePwd);
        this.linearLayoutPersonalCenterEmail = (LinearLayout) view.findViewById(R.id.linearLayoutPersonalCenterEmail);
        this.linearLayoutPersonalCenterNickName = (LinearLayout) view.findViewById(R.id.linearLayoutPersonalCenterNickName);
        this.linearLayoutPersonalCenterDes = (LinearLayout) view.findViewById(R.id.linearLayoutPersonalCenterDes);
        this.linearLayoutPersonalCenterAvatar = (LinearLayout) view.findViewById(R.id.linearLayoutPersonalCenterAvatar);
        this.textViewPersonalCenterLogout = (TextView) view.findViewById(R.id.textViewPersonalCenterLogout);
        this.imageViewPersonalCenterWXSwitch = (ImageView) view.findViewById(R.id.imageViewPersonalCenterWXSwitch);
        this.textViewPersonalCenterBindWX = (TextView) view.findViewById(R.id.textViewPersonalCenterBindWX);
        this.imageViewPersonalCenterWxLogo = (ImageView) view.findViewById(R.id.imageViewPersonalCenterWxLogo);
        this.imageViewPersonalCenterQQSwitch = (ImageView) view.findViewById(R.id.imageViewPersonalCenterQQSwitch);
        this.textViewPersonalCenterBindQQ = (TextView) view.findViewById(R.id.textViewPersonalCenterBindQQ);
        this.imageViewPersonalCenterQQLogo = (ImageView) view.findViewById(R.id.imageViewPersonalCenterQQLogo);
        this.imageViewPersonalCenterSinaSwitch = (ImageView) view.findViewById(R.id.imageViewPersonalCenterSinaSwitch);
        this.textViewPersonalCenterBindSina = (TextView) view.findViewById(R.id.textViewPersonalCenterBindSina);
        this.imageViewPersonalCenterSinaLogo = (ImageView) view.findViewById(R.id.imageViewPersonalCenterSinaLogo);
        this.textViewPersonalCenterEmail = (TextView) view.findViewById(R.id.textViewPersonalCenterEmail);
        this.textViewPersonalCenterDes = (TextView) view.findViewById(R.id.textViewPersonalCenterDes);
        this.textViewPersonalCenterNickName = (TextView) view.findViewById(R.id.textViewPersonalCenterNickName);
        this.imageViewPersonalCenterPhoto = (ImageView) view.findViewById(R.id.imageViewPersonalCenterPhoto);

        this.linearLayoutPersonalCenterAvatar.setOnClickListener(this);
        this.linearLayoutPersonalCenterDes.setOnClickListener(this);
        this.linearLayoutPersonalCenterNickName.setOnClickListener(this);
        this.linearLayoutPersonalCenterEmail.setOnClickListener(this);
        this.linearLayoutPersonalCenterChangePwd.setOnClickListener(this);

        this.imageViewPersonalCenterSinaSwitch.setOnClickListener(this);
        this.imageViewPersonalCenterQQSwitch.setOnClickListener(this);
        this.imageViewPersonalCenterWXSwitch.setOnClickListener(this);
        this.textViewPersonalCenterLogout.setOnClickListener(this);

        mContext = (MainActivity) getContext();
    }

    @Override
    protected void setupData() {
        readCaheDisplayUserinformation();
        displayBindingStatus();
    }

    private void readCaheDisplayUserinformation() {
        ImageUtil.getInstance().displayRoundedImage(mContext.getUserInformationManager().getUserInformation().getUserIcon(), imageViewPersonalCenterPhoto);
        textViewPersonalCenterEmail.setText(mContext.getUserInformationManager().getUserInformation().getUserEmail());
        textViewPersonalCenterDes.setText(mContext.getUserInformationManager().getUserInformation().getUserDescription());
        textViewPersonalCenterNickName.setText(mContext.getUserInformationManager().getUserInformation().getUserName());
    }

    //方法写的太逼了。凑合吧。
    private void displayBindingStatus() {
        displayBingingSina();

        displayBindingQQ();

        displayBindingWx();
    }

    private void displayBindingWx() {
        boolean isWxColorChanged = mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindWechat();
        textViewPersonalCenterBindWX.setSelected(isWxColorChanged);
        imageViewPersonalCenterWXSwitch.setSelected(isWxColorChanged);
        imageViewPersonalCenterWxLogo.setSelected(isWxColorChanged);

    }

    private void displayBindingQQ() {
        boolean isQqColorChanged = mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindQQ();
        textViewPersonalCenterBindQQ.setSelected(isQqColorChanged);
        imageViewPersonalCenterQQLogo.setSelected(isQqColorChanged);
        imageViewPersonalCenterQQSwitch.setSelected(isQqColorChanged);
    }

    private void displayBingingSina() {
        boolean isColorChanged = mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindWeibo();
        textViewPersonalCenterBindSina.setSelected(isColorChanged);
        imageViewPersonalCenterSinaSwitch.setSelected(isColorChanged);
        imageViewPersonalCenterSinaLogo.setSelected(isColorChanged);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.linearLayoutPersonalCenterChangePwd:
                Intent changePwdIntent = new Intent(mContext, NextstepActivity.class);
                changePwdIntent.putExtra(NextstepActivity.EXTRA_DISPLAY_TYPE, NextstepActivity.VALUE_CHANGE_PWD);
                startActivity(changePwdIntent);
                break;
            case R.id.imageViewPersonalCenterSinaSwitch:
                authorize(SinaWeibo.NAME);
                break;
            case R.id.imageViewPersonalCenterQQSwitch:
                authorize(QQ.NAME);
                break;
            case R.id.imageViewPersonalCenterWXSwitch:
                authorize(Wechat.NAME);
                break;
            case R.id.linearLayoutPersonalCenterNickName:
                Intent setNickName = new Intent(getContext(), NextstepActivity.class);
                setNickName.putExtra(NextstepActivity.EXTRA_DISPLAY_TYPE, NextstepActivity.VALUE_NAME);
                setNickName.putExtra(NextstepActivity.EXTRA_DISPLAY_ORIGINAL_CONTENT,
                        textViewPersonalCenterNickName.getText().toString());
                startActivity(setNickName);
                break;
            case R.id.linearLayoutPersonalCenterDes:
                Intent des = new Intent(getContext(), NextstepActivity.class);
                des.putExtra(NextstepActivity.EXTRA_DISPLAY_TYPE, NextstepActivity.VALUE_DESCRIPTION);
                des.putExtra(NextstepActivity.EXTRA_DISPLAY_ORIGINAL_CONTENT,
                        textViewPersonalCenterDes.getText().toString());
                startActivity(des);
                break;
            case R.id.linearLayoutPersonalCenterEmail:
                Intent email = new Intent(getContext(), NextstepActivity.class);
                email.putExtra(NextstepActivity.EXTRA_DISPLAY_TYPE, NextstepActivity.VALUE_EMAIL);
                email.putExtra(NextstepActivity.EXTRA_DISPLAY_ORIGINAL_CONTENT,
                        textViewPersonalCenterEmail.getText().toString());
                startActivity(email);
                break;
            case R.id.linearLayoutPersonalCenterAvatar:
                getImage();
                break;
            case R.id.textViewPersonalCenterLogout:
                sign_out();
                break;
        }
    }

    private SelectPhotoManager selectPhotoManager;

    private void getImage() {
        if (selectPhotoManager == null) {
            selectPhotoManager = new SelectPhotoManager();
        }
        CropOption cropOption = new CropOption();
        cropOption.style = CropOption.CropStyle.CropStyleDefault; //圆形
        selectPhotoManager.setCropOption(cropOption);
        selectPhotoManager.start(PersonalCenterFragment.this);

        selectPhotoManager.setPhotoReadyHandler(new PhotoReadyHandler() {
            @Override
            public void onPhotoReady(int from, String imgPath) {
                if (from == PhotoReadyHandler.FROM_CAMERA) {
                } else if (from == PhotoReadyHandler.FROM_ALBUM) {
                } else if (from == PhotoReadyHandler.FROM_CROP) {
                    imageFile = new File(imgPath);
                    mContext.showLoading();
                    upLoadUserInformation();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (selectPhotoManager != null) {
            selectPhotoManager.onActivityResult(requestCode, resultCode, data);
        }
    }

    //登录注册修改个人信息成功以后，调用此方法。
    @Subscribe
    public void onUpdateUserInfo(UserInformation userInformation) {
        readCaheDisplayUserinformation();
        displayBindingStatus();
    }

    private void sign_out() {
        getRequestManager().requestSingOut(NetConfigs.URL_SING_OUT, mContext.getUserInformationManager().getUserInformation().getCookie(), "", new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String json = (String) msg.obj;
                if (!TextUtils.isEmpty(json)) {
                    BaseEntity baseEntity = QDJsonUtil.Json2Object(json, BaseEntity.class);
                    if (msg.what == this.hashCode()) {
                        mContext.getUserInformationManager().removeUserInformation();
                        NetConfigs.removeCookie();
                        //send to main ,update left slider ui
                        BusProvider.getInstance().post("Logout");
                        mContext.onBackPressed();
                    } else {
                        displayToast(baseEntity.getMeta().getMsg());
                    }
                }
            }
        });
    }

    private void upLoadUserInformation() {
        String email = mContext.getUserInformationManager().getUserInformation().getUserEmail();
        String nickName = mContext.getUserInformationManager().getUserInformation().getUserName();
        String description = mContext.getUserInformationManager().getUserInformation().getUserDescription();

        getRequestManager().requestUpdatePersonalInformation(imageFile, nickName, description, email);
    }

    // third party login
    private void authorize(final String platfromName) {
        Platform platform = ShareSDK.getPlatform(getContext(), platfromName);

        if (!checkLocalThirdPary(platfromName)) {
            platform.setPlatformActionListener(PersonalCenterFragment.this);
            platform.authorize();
            return;
        }


        AlertDialog.Builder builer = new AlertDialog.Builder(getActivity());
        builer.setTitle("警告").setMessage("确定取消绑定么？");
        builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                disableThirdParty(platfromName);
            }
        });

        builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builer.show();
    }

    private boolean checkLocalThirdPary(String platfromName) {
        if (platfromName.equals("SinaWeibo")) {
            return mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindWeibo();
        } else if (platfromName.equals("QQ")) {
            return mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindQQ();
        } else if (platfromName.equals("Wechat")) {
            return mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindWechat();
        } else if (platfromName.equals("Twitter")) {
            return mContext.getUserInformationManager().getUserInformation().getUserSocial().isBindTwitter();
        }
        return false;
    }

    // third party unbind
    private void disableThirdParty(String platfromName) {
        Platform platform = ShareSDK.getPlatform(getContext(), platfromName);
        platform.removeAccount(true);
        int disableSocialType = Constants.SocialType.getSocialType(platform.getName());

        getRequestManager().requestUnBinding(disableSocialType);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        final String socialToken = platform.getDb().getToken();
        final String socialUid = platform.getDb().getUserId();
        final String socialUserName = platform.getDb().getUserName();
        final String socialUserIcon = platform.getDb().getUserIcon();
        final int socialType = Constants.SocialType.getSocialType(platform.getName());

        getRequestManager().requestSocialAction(socialUid, socialToken, socialUserName, socialUserIcon, socialType);
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        super.onRequestCallBack(params, response);
        if (params instanceof NetConfigs.RequestSocialAction ||
                params instanceof NetConfigs.RequestUpdatePersonalInformation ||
                params instanceof NetConfigs.RequestUnBinding) {
            UserCenterEntity userCenterEntity = QDJsonUtil.Json2Object(response.toString(), UserCenterEntity.class);
            if (null != userCenterEntity.getResponse() &&
                    userCenterEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200) {
                //这里我考虑的是，服务器返回的模板，我翻译成本地的保存到json里。全局使用。
                UserInformation userInformation = new UserInformation().translation(userCenterEntity);
                String userInformationJson = QDJsonUtil.getJsonString(userInformation);
                boolean isSaveCompleted = mContext.getUserInformationManager().updateUserInformation(userInformationJson);
                if (isSaveCompleted) {
                    displayBindingStatus();
                    BusProvider.getInstance().post(userInformation);
                }
            } else {
                displayToast(userCenterEntity.getMeta().getMsg());
            }
        }

        mContext.dismissLoading();
    }

    @Override
    protected void onRequestErrorCallBack(NetUtil.NetParams params, Object response) {
        super.onRequestErrorCallBack(params, response);
        mContext.dismissLoading();
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        if (action == Platform.ACTION_USER_INFOR) {
            thirdParty.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            thirdParty.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }

    private Handler thirdParty = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_AUTH_CANCEL: {
                    //取消授权
                    displayToast(R.string.auth_cancel);
                }
                break;
                case MSG_AUTH_ERROR: {
                    //授权错误
                    displayToast(R.string.auth_error);
                }
                break;
            }
        }
    };
}
